import Axios from "axios";
import { getToken, saveTokenKey } from "@/assets/overall/js/module/token";
// import { get } from "@/assets/overall/js/module/sessionStorage";
let host = "http://140.179.190.245:3303/api/";
// let host = "http://localhost:3303/api/";
let timeout = 8000
// 实例化Axios
let instance = Axios.create({
  baseURL: host,
  timeout, // 默认值是 `0` (永不超时)
});
// 请求拦截器
instance.interceptors.request.use((req) => {
  let token = getToken();
  if (token) {
    req.headers[saveTokenKey] = token;
  }
  return req;
});

let responseError = [
  {
    message: "Network Error",
    code: 500,
    tips: "服务器无法访问",
  },
  {
    message: "ECONNABORTED",
    code: 500,
    tips: "请求超时",
  },
  {
    message: "Request failed with status code 404",
    code: 404,
    tips: "接口不存在",
  },
  {
    message: `timeout of ${timeout}ms exceeded`,
    code: 4041,
    tips: "接口请求超时",
  },
];

console.log(responseError);

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (res.data.code == 0) {
      return res.data;
    } else {
      return Promise.reject(res.data);
    }
  },
  (err) => {
    let message = err.message;
    let code = err.code
    if (message == "Network Error") {
      return Promise.reject({
        code: 500,
        msg: "服务器无法访问",
      });
    } else if (code == "ECONNABORTED") {
      return Promise.reject({
        code: 500,
        msg: "请求超时",
      });
    } else if (message == "Request failed with status code 404") {
      return Promise.reject({
        code: 404,
        msg: "接口不存在",
      });
    } else {
      return Promise.reject({
        code: 5003,
        msg: "接口请求出错,未知错误",
      });
    }
  }
);
export default instance;
